﻿using System;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Data;

namespace WPFTemplateLib.WpfConverters
{
    /// <summary>
    /// 字符串或Object转圆角对象CornerRadius转换器
    /// </summary>
    public class StringToCornerRadiusConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return FromString(value + "", culture);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 从字符串转换为圆角对象（仿照微软内部方法 CornerRadiusConverter.ToString）
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="cultureInfo"></param>
        /// <returns>圆角对象</returns>
        public static CornerRadius FromString(string str, CultureInfo cultureInfo)
        {
            CornerRadius radius = new CornerRadius(0);
            if (string.IsNullOrWhiteSpace(str))
            {
                return radius;
            }

            double[] numArray = new double[4];
            int index = 0;
            var list = str.Trim().Split(',', ' ').ToList();

            for (int i = 0; i < list.Count; i++)
            {
                index = i;
                if (index >= 4)
                {
                    break;
                }

                numArray[index] = double.Parse(list[index], cultureInfo);
            }

            if (index == 0)
                return new CornerRadius(numArray[0]);
            if (index == 3)
                return new CornerRadius(numArray[0], numArray[1], numArray[2], numArray[3]);

            return radius;
        }
    }
}
